package com.ftg.learn.myself;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.ftg.learn.myself.entity.Student;
import com.ftg.learn.myself.task.ExcelTask;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author 2234
 */
public class ReadExcel {

    public static void main(String[] args) {
        String path = "d:\\成绩单.xls";
        ExecutorService task = Executors.newFixedThreadPool(5);
        EasyExcel.read(path, Student.class, new ReadListener<Student>() {

            public static final int BATCH_COUNT = 10;

            private final List<Student> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

            @Override
            public void invoke(Student o, AnalysisContext analysisContext) {
                if (o.getId() != null && o.getSno() != null && !o.getId().equals("序号")) {
                    if (cachedDataList.size() == BATCH_COUNT) {
                        task.execute(new ExcelTask(cachedDataList));
                        cachedDataList.clear();
                    }
                    cachedDataList.add(o);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                task.execute(new ExcelTask(cachedDataList));
                cachedDataList.clear();
            }

        }).sheet(0).headRowNumber(4).doRead();


        task.shutdown();
        try {
            if (!task.awaitTermination(1, TimeUnit.MINUTES)) {
                System.err.println("线程池任务未在规定时间内完成，强制关闭");
                task.shutdownNow();
            }
        } catch (InterruptedException e) {
            System.err.println("等待线程池任务完成时被中断");
            task.shutdownNow();
            Thread.currentThread().interrupt();
        }
        System.out.println("线程池已关闭");


    }

}
